<?php
declare (strict_types = 1);

namespace app;

use Error;
use think\App;
use think\exception\ValidateException;
use think\Validate;

/**
 * 控制器基础类
 */
abstract class BaseController
{
    /**
     * Request实例
     * @var \think\Request
     */
    protected $request;

    /**
     * 应用实例
     * @var \think\App
     */
    protected $app;

    /**
     * 是否批量验证
     * @var bool
     */
    protected $batchValidate = false;

    /**
     * 控制器中间件
     * @var array
     */
    protected $middleware = [];

    protected $model = null;
    protected $field = '*';
    protected $with = [];
    protected $datasArray = null;
    /**
     * 构造方法
     * @access public
     * @param  App  $app  应用对象
     */
    public function __construct(App $app)
    {
        $this->app     = $app;
        $this->request = $this->app->request;

        // 控制器初始化
        $this->initialize();
    }

    // 初始化
    protected function initialize()
    {}

    /**
     * 验证数据
     * @access protected
     * @param  array        $data     数据
     * @param  string|array $validate 验证器名或者验证规则数组
     * @param  array        $message  提示信息
     * @param  bool         $batch    是否批量验证
     * @return array|string|true
     * @throws ValidateException
     */
    protected function validate(array $data, $validate, array $message = [], bool $batch = false)
    {
        if (is_array($validate)) {
            $v = new Validate();
            $v->rule($validate);
        } else {
            if (strpos($validate, '.')) {
                // 支持场景
                [$validate, $scene] = explode('.', $validate);
            }
            $class = false !== strpos($validate, '\\') ? $validate : $this->app->parseClass('validate', $validate);
            $v     = new $class();
            if (!empty($scene)) {
                $v->scene($scene);
            }
        }

        $v->message($message);

        // 是否批量验证
        if ($batch || $this->batchValidate) {
            $v->batch(true);
        }

        return $v->failException(true)->check($data);
    }

    public function success($msg = "成功", $data = [], $count = 0, $code = 1)
    {
        return Json([
            "code" => $code,
            "count" => $count,
            "msg" => $msg,
            "data" => $data
        ]);
    }

    public function error($msg = "失败", $data = [], $code = 0)
    {
        return json([
            "code" => $code,
            "msg" => $msg,
            "data" => $data
        ]);
    }

    public function list()
    {
        $page = $this->request->param('page/d', 1);
        $limit = $this->request->param('limit/d', 10);
        try {
            $db = $this->model;
            $where = [];

            $whereArry = $this->request->param('where/a',[]);
            if (!empty($whereArry)) {
                foreach ($whereArry as $key => $value) {
                    if (!empty($value)) {
                        $where[] = [$key,'=', $value];
                    }
                }
            } 
            
            $lists = $db->with($this->with)->field($this->field)->where($where)->page($page, $limit)->select();
            $count = $db->where($where)->count();
            return $this->success('数据读取成功', $lists, $count, 0);
        } catch (\Throwable $th) {
            return $this->error('数据读取失败' . $th->getMessage());
        } 
    }

    public function add()
    {
        $datas = $this->request->param();
        if ($this->datasArray) {
            $datas = array_merge($datas, $this->datasArray);
        }
        $result = $this->model->save($datas);
        if ($result) {
            return $this->success("添加成功", $result);
        } else {
            return $this->success("添加失败", $result);
        }
    }

    /**
     * 修改数据共用方法
     * 
     * @ret int
     */
    public function edit() {
        $datas = $this->request->param();
        $data = $this->model->find($datas['id']);
        if (!$data) {
            $this->error("数据未找到");
        }
        if ($this->datasArray) {
            $datas = array_merge($datas, $this->datasArray);
        }
        if(isset($data['password']) && empty($data['password'])){
            unset($data['password']);
        }
        $res = $data->save($datas);
        if ($res) {
            return $this->success("数据修改成功",$res);
        } else {
            return $this->error("数据修改失败",$res);
        }  
    }

    public function del()
    {
        $id = $this->request->param('id');
        //var_dump($id);
        $db = $this->model;
        $result = $db->where('id',$id)->delete();
        return $this->error("删除成功",$result) ;
    }

}
